import React, { useEffect, useRef, useState, useCallback } from 'react';
import { List, Button, Toast } from 'antd-mobile';
import FormInput from '../components/FormInput';
import * as img from '../assets/image';
import useForm from 'rc-form-hooks';
import { useNavigate } from 'react-router-dom';
import Store from './store';
import {  sendMessage } from './utils';
import { browser } from 'webextension-polyfill-ts';

import { MainVersion, SubVersion, Platform } from '../config';

export default function Login() {
    const navigate = useNavigate();
    const onGoBack = () => {
        navigate(-1);
    };

    return (
        <>
            <div
                className="login_bg"
                style={{ backgroundImage: `url(${img.login_bg})` }}
            >
                <div className="login_header">
                    <img
                        className="login_back"
                        onClick={onGoBack}
                        src={img.icon_arrow_zuo_white}
                    />
                    <div className="login_title">菠萝VPN</div>
                </div>

                <img className="login_logo" src={img.icon_logo} />
                <div className="login_tabs">
                    <LoginForm />
                </div>
            </div>
        </>
    );
}

function LoginForm() {
    const navigate = useNavigate();
    const [countdown, setCountdown] = useState(Number(localStorage.Countdown));
    const { store } = Store.useContainer();
    const { connected, currentLine } = store;
    const loginEvent = useRef(false);
    const form = useForm();

    const onLogin = (res: any) => {
        if (res.Code === 0) {
            Toast.show('登录成功');
            navigate('/', { replace: true });
        } else {
            Toast.show(res.Body.ErrMsg);
        }
    };

    const onSubmit = () => {
        loginEvent.current = true;
        form.validateFields(['email', 'code'])
            .then((values) => {
                loginEvent.current = false;
                const loginData = {
                    Email: values.email,
                    VerifyCode: values.code,
                    Session: '',
                    OsType: 'IE',
                    Platform: Platform(),
                    MainVersion: MainVersion,
                    SubVersion: SubVersion,
                }
                if (connected) {
                    sendMessage({func:"loginConnect",data:{
                        loginData:loginData,
                        currentLine
                       }
                    }).then(onLogin).catch((e)=>{
                        Toast.show(e)
                    })
                 
                } else {
                    sendMessage({
                        func: 'login',
                        data: loginData,
                    }).then(onLogin).catch((e)=>{
                        Toast.show(e)
                    })
                    
                }
            })
            .catch((e) => {
                console.log(e);
            });
    };

    const emailValid = (_rules: any, value: any, callback: any) => {
        if (!value) {
            callback(new Error('邮箱必填!'));
        } else if (
            !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(value)
        ) {
            callback(new Error('输入的邮箱地址不正确!'));
        } else {
            if (loginEvent.current && value !== localStorage.Email) {
                callback(new Error('获取验证码的邮箱与登录邮箱不一致！'));
            } else {
                callback();
            }
        }
    };

    const onSendEmail = () => {
        form.validateFields(['email']).then((values) => {
            const { email } = values;
            localStorage.Email = email;
            sendMessage({func:"sendEmail",data:{ Email: email, Platform: Platform() }}).then(
                (res: any) => {
                    if (res.Code === 0) {
                        Toast.show('获取验证成功');
                    }
                }
            )
           
        });
    };

    const onChanges = useCallback((changes) => {
        if (changes.Countdown) {
            setCountdown(changes.Countdown.newValue);
        }
    }, []);

    useEffect(() => {
        browser.storage.onChanged.addListener(onChanges);
        form.setFieldsValue({ email: localStorage.Email || '' });
        return () => {
            form.resetFields();
            browser.storage.onChanged.removeListener(onChanges);
        };
    }, []);

    return (
        <div className="login_form">
            <List>
                <List.Item prefix={<img src={img.icon_mail} />}>
                    {form.getFieldDecorator('email', {
                        rules: [{ required: true, validator: emailValid }],
                    })(<FormInput placeholder="请输入邮箱" />)}
                </List.Item>
                <List.Item
                    prefix={<img src={img.icon_safecode} />}
                    extra={
                        countdown > 0 ? (
                            <div className="countdown">{countdown}S</div>
                        ) : (
                            <div className="login_code" onClick={onSendEmail}>
                                获取验证码
                            </div>
                        )
                    }
                >
                    {form.getFieldDecorator('code', {
                        rules: [{ required: true, message: '验证码必填!' }],
                    })(<FormInput placeholder="请输入邮箱验证码" />)}
                </List.Item>
            </List>

            <Button className="login_btn" color="warning" onClick={onSubmit}>
                确定
            </Button>
        </div>
    );
}
